import React, { useEffect, useRef, useState, useMemo } from 'react'

import LogicFlow from '@logicflow/core'
import { BPMNElements, Control, DndPanel, SelectionSelect } from '@logicflow/extension'
import { toast, ToastComponent } from 'amis-ui'
import { useSearchParams } from 'react-router-dom'
//import { useParams } from 'umi';

// 引入LogicFlow的样式文件
import '@logicflow/core/dist/style/index.css'
import '@logicflow/extension/lib/style/index.css'

import './common.css'

import { getDefinitionById, getDefinitionXmlById, definitionSaveXml } from '@/api'
import warmAdapter from '@/components/LogicFlow/warmAdapter'
import { FlowEditorNodeTypeEnum } from '@/enums/flowEnum'
import SettingDrawer from './Setting/Index'

type FieldType = {
  nodeCode?: string
  nodeName?: string
  listenerType?: string
  listenerPath?: string
}

import { Card } from 'antd'

export const FlowEditor: React.FC = () => {
  const [searchParams] = useSearchParams()

  const [definition, setDefinition] = useState({})
  const [definitionXml, setDefinitionXml] = useState({})

  const [settingOpen, setSettingOpen] = useState(false)

  useEffect(() => {
    async function fetchFlowDefinition() {
      const resXml = await getDefinitionXmlById({ id: searchParams.get('id') })
      setDefinitionXml(resXml.data.data)
      const res = await getDefinitionById({ id: searchParams.get('id') })
      setDefinition(res.data.data)
    }
    fetchFlowDefinition()
  }, [])

  // This ref will provide direct access to the DOM element
  const containerRef = useRef<HTMLDivElement>(null)
  const lf = useRef<LogicFlow>()
  const [skipConditionShow, setSkipConditionShow] = useState(true)
  const [flowNode, setFlowNode] = useState<Record<string, any> | null>(null)
  const disableFlowEdit = useMemo(() => {
    return searchParams.get('disabled') === 'true'
  }, [])
  useEffect(() => {
    if (containerRef.current) {
      // LogicFlow配置选项
      lf.current = new LogicFlow({
        container: containerRef.current,
        grid: {
          visible: true,
          type: 'mesh',
          size: 10,
          config: {
            color: '#eeeeee'
          }
        },
        height: 500,
        hoverOutline: false,
        edgeSelectedOutline: false,
        keyboard: {
          enabled: true
        },
        plugins: [BPMNElements, SelectionSelect, DndPanel, Control, warmAdapter]
      })

      // 拖拽面板
      lf.current.extension.dndPanel.setPatternItems([
        {
          label: '选区',
          icon: '',
          callback: () => {
            lf.current!.extension.selectionSelect.openSelectionSelect()
            lf.current!.once('selection:selected', () => {
              lf.current!.extension.selectionSelect.closeSelectionSelect()
            })
          }
        },
        {
          type: FlowEditorNodeTypeEnum.START,
          text: '开始',
          label: '开始节点',
          icon: ''
        },
        {
          type: FlowEditorNodeTypeEnum.USER_TASK,
          text: '用户任务',
          label: '用户任务',
          icon: ''
        },
        {
          type: FlowEditorNodeTypeEnum.EXCLUSIVE_GATEWAY,
          text: '排他网关',
          label: '排他网关',
          icon: ''
        },
        {
          type: FlowEditorNodeTypeEnum.PARALLEL_GATEWAY,
          text: '并行网关',
          label: '并行网关',
          icon: ''
        },
        {
          type: FlowEditorNodeTypeEnum.END,
          text: '结束',
          label: '结束节点',
          icon: ''
        }
      ])

      // 控制面板
      lf.current.extension.control.addItem({
        iconClass: 'lf-control-save',
        title: '',
        text: '保存',
        onClick: (lf: LogicFlow, ev: Event) => {
          definitionSaveXml({ id: searchParams.get('id'), xmlString: lf.getGraphData(definition) }).then(res => {
            toast.success('保存成功！', '提示')
          })
        }
      })

      // 监听被点击节点
      lf.current.on('node:click', data => {
        console.log('data.type', data)
        setFlowNode(data.data)
        setSettingOpen(true)
      })

      // 监听被点击节点
      lf.current.on('edge:click', data => {
        const nodeModel = lf.current!.getNodeModelById(data.data.sourceNodeId)
        setSkipConditionShow(nodeModel.type === FlowEditorNodeTypeEnum.EXCLUSIVE_GATEWAY)
        setFlowNode(data.data)
        setSettingOpen(true)
      })
    }
    return () => {
      lf.current = void 0
    }
  }, [])
  useEffect(() => {
    // 使用预定义的数据渲染LogicFlow图
    lf.current?.render(definitionXml)
    // 将渲染的图居中显示
    lf.current?.translateCenter()
  }, [definitionXml])

  return (
    <Card bordered={false}>
      <div style={{ display: 'flex', flexDirection: 'column', width: '100%', height: '500px' }}>
        <div className='helloworld-app getting-started'>
          <ToastComponent theme={'antd'} key='toast' position={'top-center'} />
          <div className='app-content' ref={containerRef}></div>
          {/* start Drawer */}
          <SettingDrawer
            lf={lf.current!}
            node={flowNode}
            updateNode={setFlowNode}
            open={settingOpen}
            skipConditionShow={skipConditionShow}
            disabled={disableFlowEdit}
            onClose={() => {
              setFlowNode(null)
              setSettingOpen(false)
            }}
          />
        </div>
      </div>
    </Card>
  )
}

export default FlowEditor
